package com.csmy.my.center.util.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csmy.my.center.module.CustomerInfo;
import com.csmy.my.center.util.CTConstants;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.RequestUtil;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.db.JdbcTemplateTool;

public class ChangeCPwdServlet extends HttpServlet {
	
	private static final long serialVersionUID = 2517454688474969184L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		 //进入修改密码
		String returnMsg="";
		String eflag = "";
		Dto paramDto = RequestUtil.getPraramsAsDto(req);
		String customer_id = paramDto.getAsString("customer_id");
		CustomerInfo customer = RequestUtil.getCUser(req);
		if(CTUtils.isEmpty(customer)){
			resp.sendRedirect(RequestUtil.getBasePath(req)+"/user/login");
		} else {
			
			if(StringUtil.isNotEmpty(customer_id)){

				if(!CTUtils.encryptBasedDes(paramDto.getAsString("old_password")).equals(customer.getLogin_pwd())){
					eflag = "2";
					returnMsg = "原始密码不正确";
					req.setAttribute("returl", "/cust/chpwd");
				}else{
					//处理修改数据逻辑
					String epassword = CTUtils.encryptBasedDes(paramDto.getAsString("password"));
					paramDto.put("login_pwd", epassword);
					boolean bool = JdbcTemplateTool.updateCustomerInfo(paramDto);
					if(bool){
						eflag = "1";
						returnMsg = "修改密码成功,重新登录系统";
						req.setAttribute("returl", "/user/login");
						//修改会员session信息
						customer.setLogin_pwd(epassword);
						req.getSession().removeAttribute(CTConstants.SESSION_CUSER);
						req.getSession().setAttribute(CTConstants.SESSION_CUSER, customer);
						
					}else{
						eflag = "2";
						returnMsg = "修改会员密码出错";
						req.setAttribute("returl", "/cust/chpwd");
					}
				}
			
			}
			
				req.setAttribute("eflag", eflag);
				req.setAttribute("ermsg", returnMsg);
				CustomerInfo customerInfo = JdbcTemplateTool.getCustomerInfo(customer.getCustomer_id());
				req.setAttribute("customer", customerInfo);
				req.setAttribute(CTConstants.CMENU_SELECTED_INDEX, "user_pwd");
				req.getRequestDispatcher("/customer/change_cust_pwd.jsp").forward(req, resp);
			
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
